/*
 * @Description: 
 * @Autor: zhangbing
 * @Date: 2021-08-13 11:22:29
 * @LastEditors: zhangbing
 * @LastEditTime: 2021-08-13 16:35:54
 */
import React, { useState, useEffect } from 'react';
import styles from './App.module.css';
import logo from './assets/images/logo.svg'
import Robot from './components/Robot'
// import robots from './mockdata/robots.json'
import ShoppingCart from './components/ShoppingCart'


interface Props {
  // username: string
}

interface State {
  robotGallery: any[]
  count: number
}

const App: React.FC<Props> = (props) => {

  const [count, setCount] = useState<number>(0)
  const [robotGallery, setRobotGallery] = useState<any>([])
  const [loading, setLoading] = useState<boolean>(false)
  const [error, setError] = useState<string>()

  useEffect(() => {
    document.title = `点击了${count}次`
  }, [count])

  // 第二个参数为一个空数组，就相当于在模拟类组件的生命周期函数 componentDidMount
  // 只会在组件加载的时候调用一次 
  // 这种方式非常适合我们从api访问数据，初始化state，
  useEffect(() => {

    const fetchData = async () => {
      setLoading(true)
      try {
        const responses = await fetch('https://jsonplaceholder.typicode.com/users')
        const data = await responses.json()
        setRobotGallery(data)
      } catch (e) {
        setError(e.message)
      }

      setLoading(false)
    }

    fetchData()

    // .then(res => res.json())
    // .then(data => setRobotGallery(data))
  }, [])

  // 如果 useEffect 不带第二个参数的话，就相当于在模拟 类组件中的 componentDidUpdate, 每次渲染结束的时候都会被调用

  return (
    <div className={styles.app}>
      <div className={styles.appHeader}>
        <img src={logo} alt="logo" className={styles.appLogo} />
        <h1>吊照天</h1>
      </div>
      {/* <h2>{props.username}</h2> */}
      <button onClick={() => {
        setCount(count + 1)
      }}>Click</button>
      <span>{count}</span>
      <ShoppingCart />
      {!error || error!=="" && <div>网络错误：{error}</div>}
      {!loading ?
        (<div className={styles.robotList}>
          {robotGallery.map((item) => (
            <div>
              <Robot id={item.id} name={item.name} email={item.email} />
              <p>1234</p>
            </div>

          ))}
        </div>) : <h2>loading 加载中</h2>
      }
    </div>);
}



export default App;
